package com.njlime.sys.security;

import com.njlime.core.helper.GlobalValue;
import com.njlime.core.utils.DateUtil;
import com.njlime.core.utils.StringUtil;
import com.njlime.sys.entities.Menu;
import com.njlime.sys.entities.Role;
import com.njlime.sys.entities.User;
import com.njlime.sys.repository.MenuDao;
import com.njlime.sys.security.entity.LoginFail;
import com.njlime.sys.security.session.SessionDAO;
import com.njlime.sys.security.util.CacheUtils;
import com.njlime.sys.security.util.Servlets;
import com.njlime.sys.security.util.UserUtils;
import com.njlime.sys.service.UserService;
import com.njlime.sys.util.LogUtils;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springside.modules.utils.Encodes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;

/**
 * 系统安全认证实现类
 *
 * @author Dean
 * @version 1.0
 */
@Service
public class SystemAuthorizingRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SessionDAO sessionDAO;
    @Resource
    private UserService userService;
    @Resource
    private MenuDao menuDao;
    @Resource
    private ImageCaptchaService imageCaptchaService;

    public SystemAuthorizingRealm() {
        this.setCachingEnabled(false);
    }

    /**
     * 认证回调函数, 登录时调用
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

        int activeSessionSize = sessionDAO.getActiveSessions(false).size();
        if (logger.isDebugEnabled()) {
            logger.debug("login submit, active session size: {}, username: {}", activeSessionSize, token.getUsername());
        }

        Map<String, LoginFail> loginFailMap = (Map<String, LoginFail>) CacheUtils.get("loginFailMap");
        if (loginFailMap != null) {
            LoginFail loginFail = loginFailMap.get(token.getUsername());
            if (loginFail != null && loginFail.getLoginFailCount() >= GlobalValue.MAX_LOGIN_FAIL_TIMES) {
                if (DateUtil.pastTime(loginFail.getLastFailTime(), DateUtil.PAST_MINUTES) < GlobalValue.LOGIN_FAIL_LIMIT_TIME) {
                    throw new AuthenticationException("msg:错误次数过多，不允许登录.");
                } else {
                    UserUtils.loginFail(token.getUsername(), false, true);
                }
            }
        }

        //微信登录判断
        User user = null;
        if (!StringUtil.isEmpty(token.getOpenid())) {
            user = userService.getByOpenid(token.getOpenid());
        } else {
            // 校验登录验证码
            try {
                String captchaId = UserUtils.getSession().getId().toString();
                if (token.getCaptcha() == null || !imageCaptchaService.validateResponseForID(captchaId, token.getCaptcha())) {
                    throw new AuthenticationException("msg:验证码错误, 请重试.");
                }
                user = userService.getUserByLoginName(token.getUsername());
                if (user == null) {
                    user = userService.getByMobile(token.getUsername(), true);
                }
            } catch (CaptchaServiceException e) {
                throw new AuthenticationException("msg:验证码已失效, 请重试.");
            } catch (Exception e) {
                throw new AuthenticationException("msg:验证码错误, 请重试.");
            }
        }
        // 校验用户名密码
        if (user != null) {
            if (GlobalValue.NO.equals(user.getLogin_flag())) {
                throw new AuthenticationException("msg:该帐号已禁止登录.");
            }
            byte[] salt = Encodes.decodeHex(user.getPassword().substring(0, 16));
            return new SimpleAuthenticationInfo(new Principal(user, token.isMobileLogin()),
                    user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName());
        } else {
            return null;
        }
    }

    /**
     * 获取权限授权信息，如果缓存中存在，则直接从缓存中获取，否则就重新获取， 登录成功后调用
     */
    protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            return null;
        }

        AuthorizationInfo info = null;
        Principal principal = (Principal) getAvailablePrincipal(principals);
        info = (AuthorizationInfo) CacheUtils.get(UserUtils.CACHE_AUTH_INFO_ + principal.getId());

        if (info == null) {
            info = doGetAuthorizationInfo(principals);
            if (info != null) {
                CacheUtils.put(UserUtils.CACHE_AUTH_INFO_ + principal.getId(), info);
            }
        }

        return info;
    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Principal principal = (Principal) getAvailablePrincipal(principals);
        // 获取当前已登录的用户
        if (!GlobalValue.YES.equals(GlobalValue.MULTI_ACCOUNT_LOGIN)) {
            Collection<Session> sessions = sessionDAO.getActiveSessions(true, principal, UserUtils.getSession());
            if (sessions.size() > 0) {
                // 如果是登录进来的，则踢出已在线用户
                if (UserUtils.getSubject().isAuthenticated()) {
                    for (Session session : sessions) {
                        sessionDAO.delete(session);
                    }
                }
                // 记住我进来的，并且当前用户已登录，则退出当前用户提示信息。
                else {
                    CacheUtils.remove(UserUtils.CACHE_AUTH_INFO_ + UserUtils.getUser().getId());
                    UserUtils.getSubject().logout();
                    throw new AuthenticationException("msg:账号已在其它地方登录，请重新登录。");
                }
            }
        }
        User user = userService.getUserByLoginName(principal.getLoginName());
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            List<Menu> list = new ArrayList<>();
            List<Menu> cacheList = UserUtils.getMenuList();
            list.addAll(cacheList);
            //添加调用权限
            List<Menu> extraList = new ArrayList<>();
            Set<String> menuIds = new HashSet<>();
            for (Menu menu : list) {
                if (StringUtils.isNotEmpty(menu.getTemplate())) {
                    String[] temps = menu.getTemplate().split(",");
                    for(String temp : temps){
                        if(StringUtils.isNotEmpty(temp) && !menuIds.contains(temp)) {
                            menuIds.add(temp);
                            Integer menuId = Integer.valueOf(temp);
                            extraList.add(menuDao.findOne(menuId));
                            extraList.addAll(menuDao.getMenuChildList(menuId));
                        }
                    }
                }
            }
            list.addAll(extraList);
            for (Menu menu : list) {
                if (StringUtils.isNotBlank(menu.getPermission())) {
                    // 添加基于Permission的权限信息
                    for (String permission : StringUtils.split(menu.getPermission(), ",")) {
                        info.addStringPermission(permission);
                    }
                }
                if (StringUtils.isNotBlank(menu.getUrl())) {
                    // 添加基于URL的权限信息
                    info.addStringPermission(menu.getUrl());
                }
            }
            //添加公共权限
            List<Menu> publicList = UserUtils.getPublicMenuList();
            if (publicList != null) {
                for (Menu menu : publicList) {
                    if (StringUtils.isNotBlank(menu.getUrl())) {
                        info.addStringPermission(menu.getUrl());
                    }
                }
            }


            // 添加用户权限
            info.addStringPermission("user");
            // 添加用户角色信息
            for (Role role : user.getRoleList()) {
                info.addRole(role.getName_en());
            }
            // 更新登录IP和时间
            HttpServletRequest request = Servlets.getRequest();
            user.setLogin_ip(StringUtil.getRemoteAddr(request));
            userService.updateUserLoginInfo(user);
            // 记录登录日志
            LogUtils.saveLog(request, "系统登录");
            return info;
        } else {
            return null;
        }
    }

    @Override
    protected void checkPermission(Permission permission, AuthorizationInfo info) {
        authorizationValidate(permission);
        super.checkPermission(permission, info);
    }

    @Override
    protected boolean[] isPermitted(List<Permission> permissions, AuthorizationInfo info) {
        if (permissions != null && !permissions.isEmpty()) {
            for (Permission permission : permissions) {
                authorizationValidate(permission);
            }
        }
        return super.isPermitted(permissions, info);
    }

    @Override
    public boolean isPermitted(PrincipalCollection principals, Permission permission) {
        authorizationValidate(permission);
        return super.isPermitted(principals, permission);
    }

    @Override
    protected boolean isPermittedAll(Collection<Permission> permissions, AuthorizationInfo info) {
        if (permissions != null && !permissions.isEmpty()) {
            for (Permission permission : permissions) {
                authorizationValidate(permission);
            }
        }
        return super.isPermittedAll(permissions, info);
    }

    /**
     * 授权验证方法
     *
     * @param permission
     */
    private void authorizationValidate(Permission permission) {
        // 模块授权预留接口
    }

    /**
     * 设定密码校验的Hash算法与迭代次数
     */
    /*@PostConstruct
    public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(userService.HASH_ALGORITHM);
		matcher.setHashIterations(userService.HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}*/

    /**
     * 设定密码校验的Hash算法与迭代次数
     */
    @PostConstruct
    public void initCredentialsMatcher() {
        CustomCredentialsMatcher matcher = new CustomCredentialsMatcher();
        matcher.setHashIterations(userService.HASH_INTERATIONS);
        matcher.setHashAlgorithmName(userService.HASH_ALGORITHM);
        setCredentialsMatcher(matcher);
    }

//	/**
//	 * 清空用户关联权限认证，待下次使用时重新加载
//	 */
//	public void clearCachedAuthorizationInfo(Principal principal) {
//		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
//		clearCachedAuthorizationInfo(principals);
//	}

    /**
     * 清空所有关联认证
     *
     * @Deprecated 不需要清空，授权缓存保存到session中
     */
    @Deprecated
    public void clearAllCachedAuthorizationInfo() {
//		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
//		if (cache != null) {
//			for (Object key : cache.keys()) {
//				cache.remove(key);
//			}
//		}
    }

    /**
     * 授权用户信息
     */
    public static class Principal implements Serializable {

        private static final long serialVersionUID = 1L;

        private String id; // 编号
        private String loginName; // 登录名
        private String name; // 姓名
        private boolean mobileLogin; // 是否手机登录

//		private Map<String, Object> cacheMap;

        public Principal(User user, boolean mobileLogin) {
            this.id = user.getId() + "";
            this.loginName = user.getLogin_name();
            this.name = user.getName();
            this.mobileLogin = mobileLogin;
        }

        public String getId() {
            return id;
        }

        public String getLoginName() {
            return loginName;
        }

        public String getName() {
            return name;
        }

        public boolean isMobileLogin() {
            return mobileLogin;
        }

//		@JsonIgnore
//		public Map<String, Object> getCacheMap() {
//			if (cacheMap==null){
//				cacheMap = new HashMap<String, Object>();
//			}
//			return cacheMap;
//		}

        /**
         * 获取SESSIONID
         */
        public String getSessionid() {
            try {
                return (String) UserUtils.getSession().getId();
            } catch (Exception e) {
                return "";
            }
        }

        @Override
        public String toString() {
            return id;
        }

    }
}
